package sso.intercepter;

import io.jsonwebtoken.Claims;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.web.servlet.HandlerInterceptor;
import sso.util.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class ResourceIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String receivedtoken = request.getHeader("token");
        if (receivedtoken==null || receivedtoken.equals("")){
//            throw new RuntimeException("耗子尾汁，先登录去");
            System.out.println("token为空");
        }
        if(JwtUtils.isTokenExpired(receivedtoken)){
            throw new RuntimeException("登录令牌过期了");
        }

        Claims claimsFromToken = JwtUtils.getClaimsFromToken(receivedtoken);
        List<String > authentication =(List<String>) claimsFromToken.get("authentication");

        UserDetails user = User.builder().username((String) claimsFromToken.get("username"))
                .password("4374")
                .authorities(authentication.toArray(new String[]{}))
                .build();
        PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(user, user.getPassword(), user.getAuthorities());
        token.setDetails(new WebAuthenticationDetails(request));
        SecurityContextHolder.getContext().setAuthentication(token);
        return true;
    }
}
